package fr.fbhelp.files
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	
	import fr.fbhelp.events.ParserEvent;
	import fr.fbhelp.parsing.HelpPackage;
	import fr.fbhelp.parsing.ParseManager;
	import fr.fbhelp.parsing.Toc;
	
	import mx.core.FlexGlobals;
	
	public class FileManager
	{
		public var path: PathLocator;
		
		public function FileManager()
		{
		}

		private function dispatchEvent(event:Event): void
		{
			FlexGlobals.topLevelApplication.dispatchEvent(event);
		}
		
		public function loadToc():void
		{
			path = new PathLocator();
			path.initPathes();
		}
		
		public function parseXMLConfig(helpCfgFolder:File): void
		{
			var tocParser:ParseManager = new ParseManager();
			
			var files:Array = helpCfgFolder.getDirectoryListing();
			
			for each (var f:File in files)
			{
				Output.append("Found help config file: " + f.name);
				var configXMLString:String = getFileContents(f);
				
				tocParser.parseXMLConfig(configXMLString);
			}
			
			tocParser.readHelpPackages(this);
		}
		
		private function getFileContents(file:File):String
		{
			var result:String;
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.READ);
			result = stream.readUTFBytes(stream.bytesAvailable);
			return result;
		}

		private function browseForTocFile():String
		{
			var result: String;
			var file:File = new File();
			var tocFilter:FileFilter = new FileFilter("Toc", "*.hcc;*.js;*.xml;*.txt");

			try 
			{
				Output.append("Toc File");
				file.addEventListener(Event.SELECT, onFileSelected, false, 0, true);
				file.addEventListener(IOErrorEvent.IO_ERROR, onError, false, 0, true);
				file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError, false, 0, true);
				file.browseForOpen("Open Toc File", [tocFilter]);
				//file.addEventListener(Event.SELECT, onFileSelected, false, 0, true);
			}
			catch (error:Error)
			{
				Output.append("Failed:", error.message);
			}
			return result;
		}
			
		private function onError(event:Event):void
		{
			Output.append("Error: "+event);
		}
		
		private function onFileSelected(event:Event):void
		{
			Output.append("Chosen file: " + event.target);
			var stream:FileStream = new FileStream();
			stream.open(event.target as File, FileMode.READ);
			var fileData:String = stream.readUTFBytes(stream.bytesAvailable);
			//Log.append(fileData);
			
			var loadedEvent:ParserEvent = new ParserEvent(ParserEvent.TOC_LOADED, true);
			loadedEvent.tocData = fileData;
			dispatchEvent(loadedEvent);
		}

		public function backupFile(fileName:String):void
		{
			var f:File = new File().resolvePath(fileName);
			
			if (f.exists)
			{
				var backupFile:File = new File().resolvePath(fileName + ".backup")
				f.copyTo(backupFile, true);
				Output.append("\tSaved the backup file: " + backupFile.nativePath);
			}
			else
			{
				Output.append("\tFile does not exist: " + fileName);
			}
		}
		
		public function saveFile(contents:String, fileName:String):void
		{
			if (contents == null)
			{
				return;
			}
			var f:File = new File().resolvePath(fileName);
			
			var stream:FileStream = new FileStream();
			stream.open(f, FileMode.WRITE);
			stream.writeUTFBytes(contents);
			
			Output.append("\tSaved the file: " + fileName);
		}
		
		/**
		 * Possible toc files formats:
		 * toc.hhc, helpmap.txt
		 */
		public function getTocForPackage(pkg:HelpPackage):Toc
		{
			var toc:Toc;
			var tocFolder: File = path.baseHelpSourceFolder.resolvePath("Help" + path.nativeSeparator + pkg.path);
			//Log.append("Got TOC folder: " + tocFolder.nativePath);

			var tocFile:File = tocFolder.resolvePath("toc.hhc");
			if (tocFile != null && tocFile.exists)
			{
				//trace ("Found TOC HHC file: " + tocFile.nativePath);
				toc = new Toc();
				toc.contents = getFileContents(tocFile);
				toc.type = Toc.TOC_TYPE_ADOBE_HHC_XML;
				var dec:String = tocFolder.nativePath;
				
				toc.basePath = dec;
				toc.folderName = tocFolder.name;
				// [Deprecated] toc.fileName = "topics_" + tocFolder.name + ".xml";
				toc.label = pkg.label;
			}
			if (toc == null)
			{
				tocFile = tocFolder.resolvePath("helpmap.txt");
				if (tocFile != null && tocFile.exists)
				{
					//trace ("Found TOC HelpMap file: " + tocFile.nativePath);
					toc = new Toc();
					toc.contents = getFileContents(tocFile);
					toc.type = Toc.TOC_TYPE_ADOBE_HELPMAP_TXT;
					toc.basePath = tocFolder.nativePath;
					toc.folderName = tocFolder.name;
					// [Deprecated] toc.fileName = "topics_" + tocFolder.name + ".xml";
					toc.label = pkg.label;
				}
			}
			if (tocFile == null || !tocFile.exists && tocFolder.exists)
			{
				//Log.append("No TOC File found in folder: " + tocFolder.nativePath);
				toc = new Toc();
				toc.type = Toc.TOC_TYPE_HAS_NO_SOURCE_ADOBE_TOC;
				toc.basePath = tocFolder.nativePath;
				toc.folderName = tocFolder.name;
				// [Deprecated] toc.fileName = "topics_" + tocFolder.name + ".xml";
				toc.label = pkg.label;
			}
			
			return toc;
		}
		
		public function prepareEclipseHelpIndexDeletion(): void
		{
			new HelpIndexCleaner().prepareEclipseHelpIndexDeletion(path.eclipseHelpIndexFolder);
		}
	}
}